<?php

namespace app\http\middleware;

use app\common\model\AdminRole;
use think\Controller;
use think\Db;

class Admin extends Controller
{
    public function handle($request, \Closure $next)
    {
//        判断有没有登录
        if (!session('admin.id')) {
            $this->redirect('login/index');
        }
        $this->assign('admin',session('admin'));

//        判断当前用户对于当前连接有没有访问权限
        $controller = strtolower(request()->controller());
        $action = strtolower(request()->action());
        $url = "/admin/$controller/$action";

//        查询当前操作对应的权限id
        $adminMenuId = Db::name('adminMenu')->where('url',$url)->value('id');
        if (!empty($adminMenuId)){
//            获取全部的权限id
            $menuIdArr = AdminRole::getMenusIdArr();
            if (!in_array($adminMenuId,$menuIdArr)){
//                权限不足
                $this->error("抱歉，您没有操作权限");
            }
        }
        return $next($request);
    }
}
